const { router, fs, urlencodedParser } = require('../CustomMethod');
const database = require('../CustomMethod/mysqlMethod');
const Email = require('../CustomMethod/emil.js');
const sendSmsCode = require('../CustomMethod/phone.js');
var querystring = require('querystring');
const md5 = require('../CustomMethod/md5.js');
var queryUrl = 'http://v.juhe.cn/sms/send';

// 通用函数：执行数据库查询并返回结果
const executeQuery = (res, query, params, successMsg, errorMsg, updated) => {
    database(query, params, function (err, result) {
        if (err) {
            res.send({ code: 0, module: errorMsg });
            return;
        }
        res.send({ code: 200, module: successMsg, updated, result });
    });
};

// 页面加载
router.post('/user', urlencodedParser, (req, res) => {
    let id = req.body.paramValue;
    executeQuery(res, 'SELECT name,avatar FROM userinformation where id = ?', [id], "登录成功", "用户信息获取失败", id);
});

// 邮箱验证码
router.post('/email', urlencodedParser, (req, res) => {
    let email = req.body.account;
    let yzm = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    Email(email, yzm, newCode);
    function newCode(a) {
        if (a != 1) {
            res.send({ code: 0, module: "发送失败,请检查邮箱地址" });
            return;
        } else {
            res.send({ code: 200, module: "验证码已发送至邮箱", yzm });
        }
    }
});
//手机号验证码
router.post('/phone', urlencodedParser, (req, res) => {
    let phone = req.body.account;
    let yzm = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    var queryData = querystring.stringify({
        "mobile": phone,  // 接收短信的用户手机号码
        "tpl_id": "264172",  // 您申请的短信模板ID，根据实际情况修改
        "tpl_value": "#code#=" + yzm,  // 您设置的模板变量，根据实际情况修改；无变量则为空
        "key": "8741a6d22a0498bf18dc0cfb2c263dea",  // 应用APPKEY(应用详细页查询)
    });
    sendSmsCode(queryUrl, queryData);
    res.send({ code: 200, module: "验证码已发送至手机", yzm });
});

// 注册
router.post('/register', urlencodedParser, (req, res) => {
    const name = '用户' + Date.now();
    let password = md5(req.body.password);
    const addSqlParams = [req.body.account, password, '/image/touxaing.jpg', name, 0, '-'];
    database('INSERT INTO userinformation (account,password,avatar,name,CurrentStatus,resume) VALUES(?,?,?,?,?,?)', addSqlParams, function (err, result) {
        if (err) {
            res.send({ code: 0, module: "用户名已存在" });
            return;
        }
        res.send({ code: 200, module: "注册成功" });
    });
});

// 登录
router.post('/login', urlencodedParser, (req, res) => {
    database('SELECT * FROM userinformation', [], function (err, result) {
        if (err) {
            res.send({ err: err.message });
            return;
        }
        const user = result.find(u => u.account === req.body.account);
        let password = md5(req.body.password);
        if (user) {
            if (user.password === password) {
                executeQuery(res, 'SELECT id,avatar,name FROM userinformation where account = ?', [req.body.account], "登录成功", "用户信息获取失败");
            } else {
                res.send({ code: 0, module: "登陆失败，密码错误" });
            }
        } else {
            res.send({ code: 0, module: "登陆失败，用户名不存在" });
        }
    });
});

//忘记密码
router.post('/forgetPassword', urlencodedParser, (req, res) => {
    let account = req.body.account;
    let password = md5(req.body.password);
    executeQuery(res, 'UPDATE userinformation SET password = ?  WHERE account = ?', [password, account], "密码修改成功", "密码修改失败", password);
});

// 加载修改用户信息
router.post('/personal', urlencodedParser, (req, res) => {
    let id = req.body.paramValue;
    executeQuery(res, 'SELECT avatar,name,account,password,resume FROM userinformation where id = ?', [id], "登录成功", "用户信息获取失败", id);
});

// 注销用户
router.post('/delete', urlencodedParser, (req, res) => {
    database(`DELETE FROM userinformation where id=${req.body.paramValue}`, [], function (err, result) {
        if (err) {
            res.send({ err: err.message });
            return;
        }
        res.send({ code: 200, module: "用户注销成功" });
    });
});

// 修改用户密码
router.post('/modifyPassword', urlencodedParser, (req, res) => {
    let id = req.body.paramValue;
    let password = md5(req.body.info);
    executeQuery(res, 'UPDATE userinformation SET password = ?  WHERE Id = ?', [password, id], "密码修改成功", "密码修改失败", password);
});


// 修改用户名
router.post('/modifyName', urlencodedParser, (req, res) => {
    let id = req.body.paramValue;
    let name = req.body.info;
    executeQuery(res, 'UPDATE userinformation SET name = ?  WHERE Id = ?', [name, id], "用户名修改成功", "用户名修改失败", name);
});

// 修改简历
router.post('/modifyResume', urlencodedParser, (req, res) => {
    let id = req.body.paramValue;
    let resume = req.body.resume;
    executeQuery(res, 'UPDATE userinformation SET resume = ?  WHERE Id = ?', [resume, id], "简历修改成功", "简历修改失败", resume);
})


module.exports = router;